// 游戏状态管理
const gameState = {
    difficulty: 'normal',
    crosshairStyle: 'classic',
    soundEnabled: true,
    musicEnabled: true,
    mouseSensitivity: 1.0,
    apiKey: 'sk-3fdfeb51e2a947049d95d390ac48870a',
    isPlaying: false,
    isPaused: false,
    timeLeft: 60,
    score: 0,
    shotsFired: 0,
    shotsHit: 0,
    reactionTimes: [],
    gameInterval: null,
    targetInterval: null,
    targets: [],
    backgroundPosition: { x: 0, y: 0, z: 0 }, // 添加z轴位置以增强3D效果
    maxMovement: 30 // 最大移动百分比
};

// DOM元素
const screens = {
    start: document.getElementById('start-screen'),
    settings: document.getElementById('settings-screen'),
    game: document.getElementById('game-screen'),
    pause: document.getElementById('pause-screen'),
    end: document.getElementById('end-screen')
};

const elements = {
    startBtn: document.getElementById('start-btn'),
    settingsBtn: document.getElementById('settings-btn'),
    backToStartBtn: document.getElementById('back-to-start'),
    pauseBtn: document.getElementById('pause-btn'),
    resumeBtn: document.getElementById('resume-btn'),
    restartBtn: document.getElementById('restart-btn'),
    quitBtn: document.getElementById('quit-btn'),
    playAgainBtn: document.getElementById('play-again-btn'),
    backToMenuBtn: document.getElementById('back-to-menu-btn'),
    difficultySelect: document.getElementById('difficulty'),
    crosshairStyleSelect: document.getElementById('crosshair-style'),
    mouseSensitivityInput: document.getElementById('mouse-sensitivity'),
    mouseSensitivityValue: document.getElementById('mouse-sensitivity-value'),
    apiKeyInput: document.getElementById('api-key'),
    soundCheckbox: document.getElementById('sound'),
    musicCheckbox: document.getElementById('music'),
    targetArea: document.getElementById('target-area'),
    crosshair: document.getElementById('crosshair'),
    timeLeft: document.getElementById('time-left'),
    currentScore: document.getElementById('current-score'),
    accuracy: document.getElementById('accuracy'),
    finalScore: document.getElementById('final-score'),
    finalAccuracy: document.getElementById('final-accuracy'),
    targetsHit: document.getElementById('targets-hit'),
    totalShots: document.getElementById('total-shots'),
    avgReactionTime: document.getElementById('avg-reaction-time'),
    apiScore: document.getElementById('api-score'),
    playerRating: document.getElementById('player-rating')
};

// 创建虚拟音频对象以避免错误
function createDummyAudio() {
    return {
        play: function() {},
        pause: function() {},
        load: function() {},
        currentTime: 0
    };
}

const sounds = {
    shot: document.getElementById('shot-sound') || createDummyAudio(),
    hit: document.getElementById('hit-sound') || createDummyAudio(),
    miss: document.getElementById('miss-sound') || createDummyAudio(),
    background: document.getElementById('background-music') || createDummyAudio()
};

// 难度配置
const difficultySettings = {
    easy: {
        targetSpeed: 1000, // 生成目标的速度（毫秒）
        targetLifetime: 3000, // 目标存在时间（毫秒）
        targetTypes: ['type1', 'type2'], // 目标类型
        pointsPerHit: [10, 20] // 每种目标类型的分数
    },
    normal: {
        targetSpeed: 800,
        targetLifetime: 2500,
        targetTypes: ['type1', 'type2', 'type3'],
        pointsPerHit: [10, 20, 30]
    },
    hard: {
        targetSpeed: 600,
        targetLifetime: 2000,
        targetTypes: ['type2', 'type3', 'type4'],
        pointsPerHit: [20, 30, 50]
    },
    expert: {
        targetSpeed: 400,
        targetLifetime: 1500,
        targetTypes: ['type3', 'type4'],
        pointsPerHit: [30, 50]
    }
};

// 初始化游戏
function initGame() {
    // 事件监听器
    setupEventListeners();
    
    // 隐藏所有屏幕，显示开始屏幕
    Object.values(screens).forEach(screen => screen.classList.remove('active'));
    screens.start.classList.add('active');
    
    // 确保在游戏开始前鼠标可见
    document.body.style.cursor = 'default';
    
    // 初始准心位置设置为屏幕中心
    elements.crosshair.style.left = `${window.innerWidth / 2}px`;
    elements.crosshair.style.top = `${window.innerHeight / 2}px`;
}

// 设置事件监听器
function setupEventListeners() {
    // 开始屏幕按钮
    elements.startBtn.addEventListener('click', startGame);
    elements.settingsBtn.addEventListener('click', () => showScreen('settings'));
    
    // 设置屏幕按钮
    elements.backToStartBtn.addEventListener('click', () => showScreen('start'));
    elements.difficultySelect.addEventListener('change', updateDifficulty);
    elements.crosshairStyleSelect.addEventListener('change', updateCrosshairStyle);
    elements.mouseSensitivityInput.addEventListener('input', updateMouseSensitivity);
    elements.apiKeyInput.addEventListener('change', updateApiKey);
    elements.soundCheckbox.addEventListener('change', updateSoundSettings);
    elements.musicCheckbox.addEventListener('change', updateMusicSettings);
    
    // 游戏屏幕按钮
    elements.pauseBtn.addEventListener('click', pauseGame);
    elements.targetArea.addEventListener('click', handleShoot);
    
    // 暂停屏幕按钮
    elements.resumeBtn.addEventListener('click', resumeGame);
    elements.restartBtn.addEventListener('click', restartGame);
    elements.quitBtn.addEventListener('click', quitGame);
    
    // 结束屏幕按钮
    elements.playAgainBtn.addEventListener('click', restartGame);
    elements.backToMenuBtn.addEventListener('click', quitGame);
    
    // 鼠标移动事件 - 控制背景而不是准心
    document.addEventListener('mousemove', handleMouseMove);
    
    // 禁用右键菜单
    document.addEventListener('contextmenu', (e) => e.preventDefault());
    
    // ESC键暂停游戏
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' || e.keyCode === 27) {
            if (gameState.isPlaying && !gameState.isPaused) {
                pauseGame();
            } else if (gameState.isPlaying && gameState.isPaused) {
                resumeGame();
            }
        }
    });
    
    // 窗口调整大小事件
    window.addEventListener('resize', () => {
        if (gameState.isPlaying && !gameState.isPaused) {
            // 重新定位所有目标以适应新背景位置
            updateTargetsPosition();
        }
    });
}

// 显示指定屏幕
function showScreen(screenName) {
    Object.values(screens).forEach(screen => screen.classList.remove('active'));
    screens[screenName].classList.add('active');
    
    // 确保鼠标在非游戏界面可见
    document.body.style.cursor = screenName === 'game' ? 'none' : 'default';
}

// 更新难度设置
function updateDifficulty() {
    gameState.difficulty = elements.difficultySelect.value;
}

// 更新鼠标灵敏度设置
function updateMouseSensitivity() {
    gameState.mouseSensitivity = parseFloat(elements.mouseSensitivityInput.value) || 1.0;
    elements.mouseSensitivityValue.textContent = gameState.mouseSensitivity.toFixed(1);
}

// 更新API密钥
function updateApiKey() {
    gameState.apiKey = elements.apiKeyInput.value || 'sk-3fdfeb51e2a947049d95d390ac48870a';
}

// 更新准心样式
function updateCrosshairStyle() {
    const newStyle = elements.crosshairStyleSelect.value;
    
    // 移除所有样式类
    elements.crosshair.className = 'crosshair';
    // 添加新样式类
    elements.crosshair.classList.add(newStyle);
    
    gameState.crosshairStyle = newStyle;
}

// 更新声音设置
function updateSoundSettings() {
    gameState.soundEnabled = elements.soundCheckbox.checked;
}

// 更新音乐设置
function updateMusicSettings() {
    gameState.musicEnabled = elements.musicCheckbox.checked;
    
    if (gameState.musicEnabled) {
        sounds.background.play();
    } else {
        sounds.background.pause();
    }
}

// 更新准心位置
function updateCrosshairPosition(event) {
    // 考虑准心自身尺寸，确保中心点与鼠标位置对齐
    const crosshairWidth = parseInt(window.getComputedStyle(elements.crosshair).width);
    const crosshairHeight = parseInt(window.getComputedStyle(elements.crosshair).height);
    elements.crosshair.style.left = `${event.clientX - crosshairWidth / 2}px`;
    elements.crosshair.style.top = `${event.clientY - crosshairHeight / 2}px`;
}

// 处理鼠标移动 - 只更新准心位置，不再移动背景
function handleMouseMove(event) {
    // 总是更新准心位置，无论是否在游戏中
    updateCrosshairPosition(event);
}

// 更新背景位置 - 现在保持固定位置
function updateBackgroundPosition() {
    // 保持背景固定不动
    elements.targetArea.style.transform = 'translate(0%, 0%)';
}

// 更新目标位置 - 不再需要，因为背景固定
function updateTargetsPosition() {
    // 不需要更新目标位置，因为背景固定
}

// 开始游戏
function startGame() {
    // 重置游戏状态
    resetGameState();
    
    // 更新UI
    elements.timeLeft.textContent = gameState.timeLeft;
    elements.currentScore.textContent = gameState.score;
    elements.accuracy.textContent = '0%';
    
    // 显示游戏屏幕
    showScreen('game');
    
    // 开始生成气球
    startGeneratingTargets();
    
    // 开始倒计时
    startGameTimer();
    
    // 播放背景音乐
    if (gameState.musicEnabled) {
        sounds.background.currentTime = 0;
        sounds.background.play();
    }
    
    gameState.isPlaying = true;
    
    // 隐藏鼠标指针
    document.body.style.cursor = 'none';
}

// 重置游戏状态
function resetGameState() {
    gameState.timeLeft = 60;
    gameState.score = 0;
    gameState.shotsFired = 0;
    gameState.shotsHit = 0;
    gameState.reactionTimes = [];
    gameState.isPaused = false;
    gameState.targets = [];
    gameState.backgroundPosition = { x: 0, y: 0 };
    
    // 清除现有目标
    elements.targetArea.innerHTML = '';
    
    // 重置连击计数器
    gameState.consecutiveHits = 0;
    
    // 重置背景位置
    updateBackgroundPosition();
    
    // 清除现有定时器
    if (gameState.gameInterval) {
        clearInterval(gameState.gameInterval);
    }
    if (gameState.targetInterval) {
        clearInterval(gameState.targetInterval);
    }
}

// 开始生成目标
function startGeneratingTargets() {
    const settings = difficultySettings[gameState.difficulty];
    
    gameState.targetInterval = setInterval(() => {
        if (!gameState.isPaused) {
            createTarget();
        }
    }, settings.targetSpeed);
}

// 创建目标（气球）
function createTarget() {
    // 如果游戏暂停或未开始，则不创建目标
    if (!gameState.isPlaying || gameState.isPaused) return;
    
    const settings = difficultySettings[gameState.difficulty];
    const targetTypes = settings.targetTypes;
    const randomTypeIndex = Math.floor(Math.random() * targetTypes.length);
    const targetType = targetTypes[randomTypeIndex];
    
    // 创建气球元素
    const target = document.createElement('div');
    target.className = `target ${targetType}`;
    target.dataset.type = targetType;
    target.dataset.value = settings.pointsPerHit[randomTypeIndex];
    target.dataset.spawnTime = Date.now(); // 记录生成时间用于计算反应时间
    
    // 在可见屏幕区域内随机生成位置
    const padding = 100; // 留出边距避免气球出界
    const x = Math.random() * (window.innerWidth - padding * 2) + padding;
    const y = Math.random() * (window.innerHeight - padding * 2) + padding;
    
    // 直接定位，使用translate使其居中
    target.style.left = `${x}px`;
    target.style.top = `${y}px`;
    target.style.transform = `translate(-50%, -50%)`;
    
    // 添加浮动动画
    const floatDuration = 3 + Math.random() * 2;
    target.style.animationDuration = `${floatDuration}s`;
    target.style.animation = `floatAnimation ${floatDuration}s ease-in-out ${Math.random() * 2}s infinite`;
    
    // 添加到body，确保层级正确
    document.body.appendChild(target);
    gameState.targets.push(target);
    
    // 设置气球消失的定时器
    setTimeout(() => {
        if (target.parentNode && !target.classList.contains('hit')) {
            // 自然消失动画
            target.style.transition = 'all 0.5s ease-out';
            target.style.opacity = '0';
            target.style.transform = `translate(-50%, -50%) translateY(-50px) scale(0.8)`;
            
            setTimeout(() => {
                if (target.parentNode) {
                    document.body.removeChild(target); // 从body移除
                    const index = gameState.targets.indexOf(target);
                    if (index > -1) {
                        gameState.targets.splice(index, 1);
                    }
                }
            }, 500);
        }
    }, settings.targetLifetime);
    
    // 点击事件处理 - 点击气球得分
    function handleTargetClick(event) {
        // 阻止默认行为和冒泡
        event.preventDefault();
        event.stopPropagation();
        
        // 直接调用击破函数，实现点击气球得分
        handleTargetHit(target);
    }
    
    // 添加事件监听器
    target.addEventListener('click', handleTargetClick, true); // 使用捕获阶段
    target.addEventListener('touchstart', handleTargetClick, { passive: false, capture: true });
    
    // 确保目标有正确的样式和属性
    target.style.position = 'absolute';
    target.style.zIndex = '999'; // 确保在准心下方
    target.style.cursor = 'pointer';
    target.style.pointerEvents = 'auto';
    
    // 确保准心在目标上方
    elements.crosshair.style.zIndex = '1000';
}

// 处理射击
function handleShoot(event) {
    // 播放射击音效
    if (gameState.soundEnabled) {
        sounds.shot.currentTime = 0;
        sounds.shot.play();
    }
    
    // 更新射击次数
    gameState.shotsFired++;
    
    // 检查是否击中目标（通过事件目标判断）
    if (!event.target.classList.contains('target')) {
        // 未击中，重置连击计数器
        gameState.consecutiveHits = 0;
        
        if (gameState.soundEnabled) {
            sounds.miss.currentTime = 0;
            sounds.miss.play();
        }
    }
    
    // 更新准确率
    updateAccuracy();
}

// 更新游戏统计数据
function updateGameStats(points, reactionTime) {
    // 防止负值影响
    if (points < 0) points = 0;
    
    // 增加基础分值（提高1.5倍）
    const basePoints = Math.floor(points * 1.5);
    
    // 增强反应时间奖励（提高系数）
    const timeBonus = Math.max(0, 1200 - reactionTime) * 0.15; // 反应越快，奖励越高
    
    // 添加连击奖励（每连续击中5个，额外加50分）
    gameState.consecutiveHits = gameState.consecutiveHits || 0;
    gameState.consecutiveHits++;
    const streakBonus = Math.floor(gameState.consecutiveHits / 5) * 50;
    
    // 添加难度系数奖励
    const difficultyMultiplier = {
        easy: 1.0,
        normal: 1.2,
        hard: 1.5,
        expert: 2.0
    }[gameState.difficulty];
    
    // 计算总分值
    const totalPoints = Math.floor((basePoints + Math.floor(timeBonus) + streakBonus) * difficultyMultiplier);
    gameState.score += totalPoints;
    
    // 更新UI
    elements.currentScore.textContent = gameState.score;
    updateAccuracy();
    
    // 显示连击信息（当连击数达到5的倍数时）
    if (gameState.consecutiveHits > 0 && gameState.consecutiveHits % 5 === 0) {
        showStreakMessage(`连击 ${gameState.consecutiveHits}!`);
    }
    
    return totalPoints; // 返回总分用于显示
}

// 处理气球被击中（打破气球）
function handleTargetHit(target) {
    // 防止重复点击
    if (target.classList.contains('hit')) {
        return;
    }
    
    // 播放击中音效
    if (gameState.soundEnabled) {
        sounds.hit.currentTime = 0;
        sounds.hit.play();
    }
    
    // 更新射击次数（确保点击气球时计数）
    gameState.shotsFired++;
    
    // 计算反应时间
    const spawnTime = parseInt(target.dataset.spawnTime);
    const currentTime = Date.now();
    const reactionTime = currentTime - spawnTime;
    gameState.reactionTimes.push(reactionTime);
    
    // 更新击中次数和分数
    gameState.shotsHit++;
    const points = parseInt(target.dataset.value);
    
    // 计算得分
    const totalPoints = updateGameStats(points, reactionTime);
    
    // 显示加分视觉反馈 - 增强视觉效果
    const scoreDisplay = document.createElement('div');
    scoreDisplay.className = 'points-popup';
    scoreDisplay.textContent = `+${totalPoints}`;
    scoreDisplay.style.left = target.style.left;
    scoreDisplay.style.top = target.style.top;
    scoreDisplay.style.transform = 'translate(-50%, -50%)';
    scoreDisplay.style.position = 'absolute';
    scoreDisplay.style.zIndex = '1001'; // 确保在最上层
    scoreDisplay.style.fontSize = '30px';
    scoreDisplay.style.fontWeight = 'bold';
    scoreDisplay.style.color = '#fff';
    scoreDisplay.style.textShadow = '0 0 10px rgba(255,105,180,0.8), 0 0 20px rgba(255,105,180,0.5)';
    scoreDisplay.style.opacity = '0';
    scoreDisplay.style.transition = 'all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275)';
    document.body.appendChild(scoreDisplay);
    
    // 触发动画
    setTimeout(() => {
        scoreDisplay.style.opacity = '1';
        scoreDisplay.style.transform = 'translate(-50%, -100%) scale(1.5)';
    }, 10);
    
    // 移除得分显示
    setTimeout(() => {
        scoreDisplay.style.opacity = '0';
        scoreDisplay.style.transform = 'translate(-50%, -150%) scale(0.8)';
        setTimeout(() => {
            if (scoreDisplay.parentNode) {
                document.body.removeChild(scoreDisplay);
            }
        }, 500);
    }, 1000);
    
    // 创建爆炸粒子效果
    createExplosionEffect(target);
    
    // 移除气球上可能冲突的transform属性，让爆炸动画能正确执行
    target.style.transform = 'translate(-50%, -50%)';
    
    // 标记气球为已击中
    target.classList.add('hit');
    
    // 气球爆炸效果
    target.style.transition = 'all 0.3s ease-out';
    target.style.transform = 'translate(-50%, -50%) scale(1.3) rotate(10deg)';
    target.style.opacity = '0';
    
    // 等待动画完成后再移除，确保用户能看到爆炸效果
    setTimeout(() => {
        if (target.parentNode) {
            document.body.removeChild(target); // 从body移除
            const index = gameState.targets.indexOf(target);
            if (index > -1) {
                gameState.targets.splice(index, 1);
            }
        }
    }, 300); // 与CSS动画时间匹配
}

// 更新准确率
function updateAccuracy() {
    if (gameState.shotsFired === 0) {
        elements.accuracy.textContent = '0%';
        return;
    }
    
    const accuracyPercent = Math.round((gameState.shotsHit / gameState.shotsFired) * 100);
    elements.accuracy.textContent = `${accuracyPercent}%`;
}

// 显示加分视觉反馈
function showPointsPopup(target, points) {
    const popup = document.createElement('div');
    popup.className = 'points-popup';
    popup.textContent = `+${points}`;
    
    // 获取目标位置
    const targetRect = target.getBoundingClientRect();
    const x = targetRect.left + targetRect.width / 2;
    const y = targetRect.top + targetRect.height / 2;
    
    // 设置初始位置
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    
    // 添加到body
    document.body.appendChild(popup);
    
    // 动画结束后移除
    setTimeout(() => {
        popup.classList.add('fade-out');
        setTimeout(() => {
            if (popup.parentNode) {
                document.body.removeChild(popup);
            }
        }, 800);
    }, 10);
}

// 显示连击信息
function showStreakMessage(message) {
    const streakMsg = document.createElement('div');
    streakMsg.className = 'streak-message';
    streakMsg.textContent = message;
    
    // 添加到body
    document.body.appendChild(streakMsg);
    
    // 动画结束后移除
    setTimeout(() => {
        streakMsg.classList.add('fade-out');
        setTimeout(() => {
            if (streakMsg.parentNode) {
                document.body.removeChild(streakMsg);
            }
        }, 1500);
    }, 10);
}

// 开始游戏计时器
function startGameTimer() {
    gameState.gameInterval = setInterval(async () => {
        if (!gameState.isPaused) {
            gameState.timeLeft--;
            elements.timeLeft.textContent = gameState.timeLeft;
            
            // 游戏结束
            if (gameState.timeLeft <= 0) {
                await endGame();
            }
        }
    }, 1000);
}

// 暂停游戏
function pauseGame() {
    gameState.isPaused = true;
    showScreen('pause');
    
    // 暂停背景音乐
    if (gameState.musicEnabled) {
        sounds.background.pause();
    }
}

// 恢复游戏
function resumeGame() {
    gameState.isPaused = false;
    showScreen('game');
    
    // 恢复背景音乐
    if (gameState.musicEnabled) {
        sounds.background.play();
    }
    
    // 隐藏鼠标指针
    document.body.style.cursor = 'none';
}

// 重新开始游戏
function restartGame() {
    resetGameState();
    startGame();
}

// 退出游戏
function quitGame() {
    resetGameState();
    showScreen('start');
    
    // 停止背景音乐
    sounds.background.pause();
    
    // 显示鼠标指针
    document.body.style.cursor = 'default';
}

// 计算平均反应时间
function calculateAverageReactionTime() {
    if (gameState.reactionTimes.length === 0) return 0;
    
    const sum = gameState.reactionTimes.reduce((acc, time) => acc + time, 0);
    return Math.round(sum / gameState.reactionTimes.length);
}

// 使用API进行评分
async function calculateApiScore() {
    try {
        // 准备评分数据
        const accuracyPercent = gameState.shotsFired > 0 
            ? (gameState.shotsHit / gameState.shotsFired) * 100 
            : 0;
        
        const avgReactionTime = calculateAverageReactionTime();
        const targetsPerMinute = gameState.shotsHit;
        
        // 构建API请求数据
        const requestData = {
            score: gameState.score,
            accuracy: accuracyPercent,
            reactionTime: avgReactionTime,
            targetsHit: targetsPerMinute,
            difficulty: gameState.difficulty
        };
        
        // 这里我们使用本地计算的方式模拟API评分
        // 在实际应用中，这里应该发送HTTP请求到评分API
        
        // 本地计算评分算法
        const accuracyScore = (accuracyPercent / 100) * 40;
        const reactionScore = Math.max(0, 30 - (avgReactionTime / 100));
        const difficultyMultiplier = {
            easy: 0.5,
            normal: 1.0,
            hard: 1.5,
            expert: 2.0
        }[gameState.difficulty];
        const targetsScore = Math.min(30, (targetsPerMinute * difficultyMultiplier) * 0.3);
        
        const apiScore = Math.round(accuracyScore + reactionScore + targetsScore);
        
        return Math.max(0, Math.min(100, apiScore));
    } catch (error) {
        console.error('API评分计算失败:', error);
        return 0;
    }
}

// 创建爆炸效果
function createExplosionEffect(target) {
    // 获取气球的位置
    const rect = target.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    // 根据气球类型确定颜色
    let color = '#ffffff'; // 默认颜色
    if (target.classList.contains('type1')) color = '#ff6b6b';
    else if (target.classList.contains('type2')) color = '#ff8e53';
    else if (target.classList.contains('type3')) color = '#feca57';
    else if (target.classList.contains('type4')) color = '#48dbfb';
    
    // 增加粒子数量，使爆炸效果更明显
    const particleCount = 15;
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        
        // 设置粒子样式，增加大小和多样性
        particle.style.position = 'fixed';
        particle.style.width = `${3 + Math.random() * 4}px`;
        particle.style.height = `${3 + Math.random() * 4}px`;
        particle.style.borderRadius = '50%';
        particle.style.backgroundColor = color;
        particle.style.left = `${centerX}px`;
        particle.style.top = `${centerY}px`;
        particle.style.pointerEvents = 'none';
        particle.style.zIndex = '1001';
        particle.style.boxShadow = `0 0 10px ${color}`;
        
        // 添加到DOM
        document.body.appendChild(particle);
        
        // 计算随机的爆炸方向和距离，增加随机性
        const angle = (i / particleCount) * Math.PI * 2 + (Math.random() * 0.5 - 0.25);
        const distance = 25 + Math.random() * 15;
        const moveX = Math.cos(angle) * distance;
        const moveY = Math.sin(angle) * distance;
        
        // 应用动画，增加持续时间和变化
        const animationDuration = 600 + Math.random() * 200;
        particle.animate([
            { transform: 'translate(-50%, -50%) scale(1)', opacity: 1 },
            { transform: `translate(calc(-50% + ${moveX}px), calc(-50% + ${moveY}px)) scale(0.8)`, opacity: 0.8, offset: 0.3 },
            { transform: `translate(calc(-50% + ${moveX}px), calc(-50% + ${moveY}px)) scale(0)`, opacity: 0 }
        ], {
            duration: animationDuration,
            easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
        });
        
        // 动画结束后移除粒子
        setTimeout(() => {
            if (particle.parentNode) {
                document.body.removeChild(particle);
            }
        }, animationDuration);
    }
    
    // 添加一个中心闪光效果
    const flash = document.createElement('div');
    flash.style.position = 'fixed';
    flash.style.width = '30px';
    flash.style.height = '30px';
    flash.style.borderRadius = '50%';
    flash.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
    flash.style.boxShadow = `0 0 20px rgba(255, 255, 255, 0.8)`;
    flash.style.left = `${centerX}px`;
    flash.style.top = `${centerY}px`;
    flash.style.pointerEvents = 'none';
    flash.style.zIndex = '1002';
    
    document.body.appendChild(flash);
    
    // 闪光动画
    flash.animate([
        { transform: 'translate(-50%, -50%) scale(0)', opacity: 1 },
        { transform: 'translate(-50%, -50%) scale(1.2)', opacity: 0.6, offset: 0.3 },
        { transform: 'translate(-50%, -50%) scale(1.5)', opacity: 0 }
    ], {
        duration: 400,
        easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
    });
    
    // 移除闪光
    setTimeout(() => {
        if (flash.parentNode) {
            document.body.removeChild(flash);
        }
    }, 400);
}

// 结束游戏
async function endGame() {
    gameState.isPlaying = false;
    
    // 清除定时器
    clearInterval(gameState.gameInterval);
    clearInterval(gameState.targetInterval);
    
    // 移除所有气球
    elements.targetArea.innerHTML = '';
    gameState.targets = [];
    
    // 计算最终数据
    const accuracyPercent = gameState.shotsFired > 0 
        ? Math.round((gameState.shotsHit / gameState.shotsFired) * 100) 
        : 0;
    
    const avgReactionTime = calculateAverageReactionTime();
    const apiScore = await calculateApiScore();
    
    // 更新结束屏幕
    elements.finalScore.textContent = gameState.score;
    elements.finalAccuracy.textContent = `${accuracyPercent}%`;
    elements.targetsHit.textContent = gameState.shotsHit;
    elements.totalShots.textContent = gameState.shotsFired;
    elements.avgReactionTime.textContent = `${avgReactionTime}ms`;
    elements.apiScore.textContent = apiScore;
    elements.playerRating.textContent = calculateRating(gameState.score, accuracyPercent, apiScore);
    
    // 显示结束屏幕
    showScreen('end');
    
    // 停止背景音乐
    sounds.background.pause();
    
    // 显示鼠标指针
    document.body.style.cursor = 'default';
}

// 计算评级 - 加入API评分因素
function calculateRating(score, accuracy, apiScore) {
    // 综合评分计算
    const scoreFactor = Math.min(1, score / 2000);
    const accuracyFactor = accuracy / 100;
    const apiFactor = apiScore / 100;
    
    const compositeScore = (scoreFactor * 0.4) + (accuracyFactor * 0.3) + (apiFactor * 0.3);
    
    if (compositeScore >= 0.95) return '枪神';
    if (compositeScore >= 0.85) return '传奇大师';
    if (compositeScore >= 0.75) return '全球精英';
    if (compositeScore >= 0.65) return '大师级守卫';
    if (compositeScore >= 0.55) return '黄金新星';
    if (compositeScore >= 0.45) return '白银精英';
    if (compositeScore >= 0.35) return '勇敢的新手';
    return '新兵';
}

// 当页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    initGame();
});